<?php
/**
 * Created by dh2y.
 * Blog: http://blog.csdn.net/sinat_22878395
 * Date: 2020/1/31 14:19
 * For:
 */

namespace app\admin\service;


use app\admin\validate\AuthGroup;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\traits\Result;
use think\exception\ValidateException;

class AuthGroupService
{
    use Result;

    private static $sceneMsg = [
        'add' => '添加',
        'edit' => '编辑',
        'access' => '赋权'
    ];

    /**
     * 添加/编辑角色
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeRole($data,$scene='add'){
        $data['state'] = isset( $data['state'])? $data['state']:0;
        try {
            validate(AuthGroup::class)->scene($scene)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg =Result::error($e->getError(),null, ['token'=>request()->buildToken()]);
            return $msg;
        }

        $model = new AuthGroupModel();

        //编辑 赋权
        if ($scene !='add') {
            $result = $model->exists(true)->update($data);
        } else {
            $result = $model->create($data);
        }

        if ($result) {
            return Result::success(self::$sceneMsg[$scene].'成功');
        } else {
            return Result::error(self::$sceneMsg[$scene].'失败');
        }
    }

}